package org.glut.wechat.personalcenter.filter;

import io.jsonwebtoken.JwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.glut.wechat.personalcenter.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws ServletException, IOException {

        // 1. 清空旧的安全上下文
        SecurityContextHolder.clearContext();

        // 2. 提取 Token
        String token = getTokenFromRequest(request);

        // 3. 处理 Token 认证
        if (token != null) {
            try {
                // 验证并解析 Token
                Integer userId = jwtUtil.getUserIdFromToken(token);

                // 赋予基础权限（避免权限校验报错）
                List<GrantedAuthority> authorities = Collections.singletonList(
                        new SimpleGrantedAuthority("ROLE_USER")
                );

                // 构造规范的认证对象
                Authentication authentication = new UsernamePasswordAuthenticationToken(
                        userId,
                        null,
                        authorities
                );

                // 设置安全上下文
                SecurityContextHolder.getContext().setAuthentication(authentication);

            } catch (JwtException e) {
                // Token 无效时返回401
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token 无效或已过期");
                return; // 终止过滤链，不再继续处理
            }
        } else {
            // Token 缺失时，设置匿名认证（可选）
            Authentication anonymousAuth = new AnonymousAuthenticationToken(
                    "anonymous",
                    "anonymousUser",
                    Collections.singletonList(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))
            );
            SecurityContextHolder.getContext().setAuthentication(anonymousAuth);
        }

        // 4. 继续执行过滤链
        filterChain.doFilter(request, response);
    }

    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken == null) {
            bearerToken = request.getHeader("authorization");
        }
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}